<script setup>
import {onMounted, reactive, ref, computed} from "vue";
import {ElCard, ElTimeline, ElTimelineItem} from 'element-plus'
import {showImagePreview, showLoadingToast, showToast} from "vant";
import api from "../libs/api";
import moment from 'moment';
import {useLineStore} from "../store/useLineStore";
import 'element-plus/dist/index.css'
const lineStore = useLineStore()
const loading = ref(false);
const finished = ref(false);
const error = ref(false);
const refreshing = ref(false);
const onLoad = () => {
  try {
    findList()
  } catch (e) {
    error.value = true
  }
}

const me = ref({})
onMounted(() => {
  api.get('/api/user').then(res => {
    me.value = res.data
  })
})

const onRefresh = () => {
  try {
    if (refreshing.value) {
      pageNum.value = 0
      finished.value = false
      lineStore.setLines([])
      findList()
    }
  } catch (e) {
    refreshing.value = false
  }
}

const list = computed(() => lineStore.getLines);
const pageNum = ref(0)
const pageSize = ref(10)
const findList = () => {
  const data = {
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  const load = showLoadingToast('加载中')
  api.get('/api/line/list', {params: data}).then((res) => {
    if (res.status === 200) {
      if (res.data.length < 1) {
        finished.value = true;
      } else {
        let newArr = []
        for (const a of res.data) {
          a.picture = handlerImage(a.picture)
        }
        newArr.unshift(...res.data)
        let array = list.value
        newArr.unshift(...array)

        lineStore.setLines(newArr)
        loading.value = false
        refreshing.value = false
        pageNum.value = pageNum.value + 1
      }
    } else {
      showToast('加载异常');
    }
  }).finally(() => load.close())
}

const handlerImage = (file) => {
  if (file !== undefined) {
    return JSON.parse(file)
  } else {
    return []
  }
}

const onPreview = (file,e) => {
  console.log(file)
  console.log(e)
  console.log(e)
  showImagePreview({
    images: [file.content],
    closeable: true,
  });
}

const handlerTime = (item) => {
  const time = moment(item.line_time).format('yyyy-M-d HH:mm')
  const did = JSON.parse(item.did)
  return did.fullName + ' 发布于 ' + time
}


const add = () => {
  showBottom.value = !showBottom.value
}

const isOverSize = (file) => {
  const maxSize = 2 * 1024 * 1024;
  return file.size >= maxSize;
}
const onOversize = (file) => {
  showToast('文件大小不能超过2M');
};

// 返回布尔值
const beforeRead = (file) => {

  if (file.length > 1) {
    for (const fileElement of file) {
      if (fileElement.type !== 'image/jpeg'
        && fileElement.type !== 'image/jpg'
        && fileElement.type !== 'image/gif'
        && fileElement.type !== 'image/png') {
        showToast('图片格式包括：jpeg、jpg、gif、png');
        return false;
      }
    }
  } else {
    if (file.type !== 'image/jpeg'
      && file.type !== 'image/jpg'
      && file.type !== 'image/gif'
      && file.type !== 'image/png') {
      showToast('图片格式包括：jpeg、jpg、gif、png');
      return false;
    }
  }
  return true;
};

const fileList = ref([]);

const showBottom = ref(false)
const form = reactive({
  did: '',
  des: '',
  picture: null,
  line_time: null,
})
const sub = () => {
  const loading = showLoadingToast('正在提交')
  form.picture = JSON.stringify(fileList.value)
  form.line_time = new Date()
  form.did = JSON.stringify(me.value)
  api.post('/api/line/create', form).then((res) => {
    if (res.status === 200) {
      showToast("已完成")
      showBottom.value = false

      let data = res.data
      data.picture = handlerImage(data.picture)
      lineStore.updateLines(data)
      form.des = ''
      form.picture = null
      fileList.value = []
    } else {
      showToast("错误请重试")
    }
  }).catch(e=>{
    showToast(e.message)
  }).finally(() => loading.close())
}
</script>

<template>
  <div class="sdf98dsff">
    <van-nav-bar safe-area-inset-top color="grey" title="Time-Line"/>
    <div class="sdffvg34f" ref="divRef">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <el-timeline>
          <van-list
            v-model:loading="loading"
            :finished="finished"
            v-model:error="error"
            error-text="请求失败，点击重新加载"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <el-timeline-item
              placement="top"
              hollow
              type="primary"
              v-for="(item, index) in list" :key="index"
              :timestamp="handlerTime(item)"
            >
              <el-card>
                <div v-if="item.des === ''" style="color: lightgrey">
                  什么都没写~
                </div>
                <div v-if="item.des !== ''">
                  {{ item.des }}
                </div>
                <div style="padding-top: 10px">
                  <van-uploader
                    v-if="item.picture.length > 0"
                    :deletable="false"
                    :preview-full-image="false"
                    @click-preview="onPreview"
                    :max-count="item.picture.length"
                    v-model="item.picture"/>
                </div>
              </el-card>
            </el-timeline-item>
          </van-list>
        </el-timeline>
      </van-pull-refresh>
      <div class="dffs">
        <van-back-top target=".sdffvg34f"/>
        <van-icon v-if="!showBottom" name="plus" size="20" @click="add"/>
        <van-icon v-if="showBottom" name="cross" size="20" @click="add"/>
      </div>
    </div>
    <van-popup
      round
      safe-area-inset-bottom
      closeable
      v-model:show="showBottom"
      position="bottom"
      :style="{ height: '80%',  backgroundColor: '#eeeeee' }">
      <div style="padding: 50px 0;height:80%">
        <van-cell-group inset>
          <van-field
            rows="2"
            show-word-limit
            clearable autosize
            v-model="form.des"
            type="textarea"
            maxlength="500"
            placeholder="有什么想法"/>
          <div style="padding: 20px 16px">
            <van-uploader
              multiple
              v-model="fileList"
              :max-count="9"
              :max-size="isOverSize"
              @oversize="onOversize"
              :before-read="beforeRead"/>
          </div>

        </van-cell-group>
        <div style="padding: 40px">
          <van-button color="#1DC1C7" block @click="sub">提交</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.sdf98dsff {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #eeeeee;
  display: flex;
  flex-direction: column;
}

.sdffvg34f {
  height: 100%;
  padding: 10px 15px 15px 10px;
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.sdffvg34f::-webkit-scrollbar {
  width: 0 !important;
  display: none;
}

.dffs {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  width: var(--van-back-top-size);
  height: var(--van-back-top-size);
  right: var(--van-back-top-right);
  bottom: var(--van-back-top-bottom);
  z-index: var(--van-back-top-z-index);
  cursor: pointer;
  color: var(--van-back-top-text-color);
  border-radius: var(--van-radius-max);
  box-shadow: 0 2px 8px rgb(0 0 0 / 12%);
  transform: scale(1);
  transition: var(--van-duration-base) cubic-bezier(.25, .8, .5, 1);
  background-color: var(--van-back-top-background);
}


</style>

<style>
.el-timeline-item__tail {
  border-left: 2px solid lightgrey;
}

.dsaff {
  width: 100%;
  height: 300px;
  background-color: grey;

}
</style>
